import re

import jsonpath
import pytest


from commons.sessions import Session
from commons.tools import value_displace_var, assert_equals

# @pytest.fixture(scope="session")
# def sessions():
#     return Session()

sessions = Session()


@pytest.fixture(scope="session")
def getAuthentication():
    resp = sessions.request(
        method="POST",
        url="https://beta-apis.wanxue.cn/auth/oauth/token",
        params={
            "grant_type": "password",
            "client_id": "qfRZaXirA7TeT8pb",
            "username": "15732069727",
            "password": "c51cd8e64b0aeb778364765013df9ebe"
        }

    )
    print(resp.json())
    # 判断登录是否成功
    assert "access_token" in resp.json()
    sessions.headers = {
        "Authorization": "Bearer " + resp.json()["access_token"]
    }
    sessions.uid = resp.json()["uid"]
    yield sessions


temp_data = {}


def pytest_yaml_run_step(item):  # yaml用例的每一个步骤（step）都会调用一次本hook
    print(item)
    print("当前用例名称：", item.name)
    print("当前用例内容：", item.yaml_data)
    print("当前用例步骤：", item.current_step)
    print(set(item.current_step.keys()))

    for yaml_key, yaml_value in item.current_step.items():
        print(yaml_key, yaml_value)
        yaml_value=value_displace_var(yaml_value, temp_data)

        if "request" == yaml_key:
            item.resp = sessions.request(**yaml_value)
            print(item.resp.json())
            print(item.resp.request.headers,"<<<<<<<<<<<<<<<<<<<<<<")
        elif "extract" == yaml_key:
            for extr_key, extr_value in yaml_value.items():
                extract_method, expression, index = extr_value
                if extract_method == "json":
                    data = getattr(item.resp, extract_method)()
                    value = jsonpath.jsonpath(data, expression)[index]
                else:
                    data = getattr(item.resp, extract_method)
                    value = re.findall(expression, data)[index]
                print(value)
                temp_data[extr_key] = value
        elif "validate" in yaml_key:
            print(yaml_value,"断言7777777777777")
            for assert_way,assert_content in yaml_value.items():
                if assert_way=="equals":
                    print("进入断言")
                    for assert_msg,assert_data in assert_content.items():
                        print(assert_msg,assert_data[1],assert_data[0])
                        assert_equals(assert_msg,assert_data[1],assert_data[0])
    return True

